/** @odoo-module **/
 
import {registry} from "@web/core/registry";
async function jiazaijs1(url) {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url;
      script.type = 'text/javascript';
      script.onload = () => resolve(`Script loaded: ${url}`);
      script.onerror = () => reject(new Error(`Failed to load script: ${url}`));
      document.head.appendChild(script);
      return script;
    });
  }
  async function jiazaihprint() {
    if (!window.a==true) {
        try {
            let result = await jiazaijs1("/hiwprint/static/src/hiprint/plugins/jq-3.31.js");
            result = await jiazaijs1("/hiwprint/static/src/hiprint/content/bootstrap.min.js");
            result = await jiazaijs1("/hiwprint/static/src/hiprint/polyfill.min.js");
            result = await jiazaijs1("/hiwprint/static/src/hiprint/plugins/jquery.minicolors.min.js");
         result = await jiazaijs1("/hiwprint/static/src/hiprint/plugins/JsBarcode.all.min.js");
         result = await jiazaijs1("/hiwprint/static/src/hiprint/plugins/qrcode.js");
         result = await jiazaijs1("/hiwprint/static/src/hiprint/hiprint.bundle.js");
         result = await jiazaijs1("/hiwprint/static/src/hiprint/plugins/jquery.hiwprint.js");
         window.a=true;                      
        } catch (err) {
            console.error(err);
        }
       }
       await jiazaijs1("/hiwprint/static/src/hiprint/hiprint.bundle.js");
  }

  function flattenObject1(obj, prefix = "") {
    const result = {};
    for (const key in obj) {
      const value = obj[key];
      const newKey = prefix ? `${prefix}_${key}` : key;

      if (
        typeof value === "object" &&
        value !== null &&
        !Array.isArray(value)
      ) {
        if ("id" in value || "display_name" in value) {
          if ("id" in value) result[`${newKey}_id`] = value.id;
          if ("display_name" in value)
            result[`${newKey}_display_name`] = value.display_name; // ← 修改点
        } else {
          Object.assign(result, flattenObject(value, newKey));
        }
      } else if (!Array.isArray(value)) {
        result[newKey] = value;
      }
    }
    return result;
  }
  function flattenObject(obj, prefix = "") {
    const result = {};
    for (const key in obj) {
      const value = obj[key];
      const newKey = prefix ? `${prefix}_${key}` : key;
  
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        // 如果是简单对象，扁平化每一个字段
        for (const subKey in value) {
          const subValue = value[subKey];
          if (typeof subValue !== "object" && !Array.isArray(subValue)) {
            result[`${newKey}_${subKey}`] = subValue;
          }
        }
      } else if (!Array.isArray(value)) {
        result[newKey] = value;
      }
    }
    return result;
  }
  
  function flattenArrayField(arr) {
    return arr.map((item) => {
      const row = {};
      for (const key in item) {
        const value = item[key];

        if (Array.isArray(value)) {
          continue; // 跳过二级数组
        } else if (typeof value === "object" && value !== null) {
          Object.assign(row, flattenSingleLevelObject(value, key));
        } else {
          row[key] = value;
        }
      }
      return row;
    });
  }
  function flattenSingleLevelObject(obj, prefix) {
    const result = {};
    for (const key in obj) {
      const value = obj[key];
      if (
        typeof value !== "object" ||
        value === null ||
        Array.isArray(value)
      ) {
        result[`${prefix}_${key}`] = value;
      }
    }
    return result;
  }
  function transformData1(data) {
    const result = {};
    const firstObj = data[0];

    for (const key in firstObj) {
      const value = firstObj[key];

      if (Array.isArray(value)) {
        result[key] = flattenArrayField(value);
      } else if (typeof value === "object" && value !== null) {
        if ("id" in value || "display_name" in value) {
          if ("id" in value) result[`${key}_id`] = value.id;
          if ("display_name" in value)
            result[`${key}_display_name`] = value.display_name; // ← 修改点
        } else {
          Object.assign(result, flattenObject(value, key));
        }
      } else {
        result[key] = value;
      }
    }

    return result;
  }
  function transformData(data) {
    const result = {};
    const firstObj = data[0];

    for (const key in firstObj) {
      const value = firstObj[key];

      if (Array.isArray(value)) {
        result[key] = flattenArrayField(value);
      } else if (typeof value === "object" && value !== null) {
       
          Object.assign(result, flattenObject(value, key));
        
      } else {
        result[key] = value;
      }
    }

    return result;
  }
  function randomString(length = 8) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }
  function transformFields(fields) {
    const normalFields = [];
    const tableMap = {};

    function getTopParent(field) {
      while (field.parent) {
        field = field.parent;
      }
      return field;
    }

    for (const field of fields) {
      const id = field.id;

      // 普通字段（无 '/' 且类型不是 many2one/one2many/many2many）
      if (
        !id.includes("/") &&
        (!field.field_type || !field.field_type.includes("2many"))
      ) {
        normalFields.push({
          tid: `configModule.${id}`,
          title: field.string.split("/").pop(),
          field: id,

          data: "",
          type: "text",
        });
      }
    }

    for (const field of fields) {
      const id = field.id;

      // 嵌套字段（带 '/'）
      if (id.includes("/")) {
        const parts = id.split("/");
        const lastPart = parts[parts.length - 1];

        // 查找最顶层 parent，如果是 one2many 或 many2many，属于表格字段
        if (field.parent) {
          const top = getTopParent(field);
          const tableId = top.id;

          if (["one2many", "many2many"].includes(top.field_type)) {
            tableMap[tableId] = tableMap[tableId] || {
              tid: `configModule.${tableId}`,
              field: tableId,
              title: top.string,
              type: "table",
              editable: true,
              columnDisplayEditable: true,
              columnDisplayIndexEditable: true,
              columnTitleEditable: true,
              columnResizable: true,
              columnAlignEditable: true,
              columns: [[]],
            };

            //const fieldKey = id.replace(/\//g, "_").replace(/\./g, "");
            const parts = id.split("/");
            const fieldKey = parts.slice(1).join("_"); // 去掉顶层字段（如 order_line）
            const fieldTitle = field.string.split("/").pop();

            tableMap[tableId].columns[0].push({
              title: fieldTitle,
              align: "center",
              field: fieldKey,
              width: 100,
            });
          } else {
            // 顶层不是 one2many 表格字段，直接作为普通字段处理
            normalFields.push({
              tid: `configModule.${id.replace(/\//g, "_")}`,
              title: field.string.split("/").pop(),
              field: id.replace(/\//g, "_"),
              data: "",
              type: "text",
            });
          }
        } else {
          // 无 parent 直接保留为普通字段
          normalFields.push({
            tid: `configModule.${id.replace(/\//g, "_")}`,
            title: field.string.split("/").pop(),
            field: id.replace(/\//g, "_"),
            data: "",
            type: "text",
          });
        }
      }
    }

    return [...normalFields, ...Object.values(tableMap)];
  }
  function buildSpecification(fields) {
    const spec = {};
  
    for (const field of fields) {
      const path = field.id.split("/");
      let current = spec;
  
      for (let i = 0; i < path.length; i++) {
        const part = path[i];
  
        if (i === path.length - 1) {
          // 最后一层字段
          if (!current[part]) {
            current[part] = {};
          }
        } else {
          // 中间层（one2many 或 many2one 关系字段）
          if (!current[part]) {
            current[part] = { fields: {} };
          }
          if (!current[part].fields) {
            current[part].fields = {};
          }
          current = current[part].fields;
        }
      }
    }
  
    return spec;
  }
  
registry
    .category("ir.actions.report handlers")
    .add("abchandle", async function (action, options, env) {
        console.log( action);
        const { orm, notification } = env.services;

        try {
          // 假设 action.reportId 就是 ir.actions.report 的 ID
          const reportId = action.id;
    
          // 第一步：根据 report_id 反查 hiwprint.hiwprint 记录
          const records = await orm.searchRead(
            "hiwprint.hiwprint",
            [["report_id", "=", reportId]],
            ["id", "ziduans", "moban", "moxing", "moxing_model_name"]
          );
    
          if (records.length === 0) {
            notification.add("未找到关联的 hiwprint 记录", { type: "warning" });
            return false;
          }
    
          const record = records[0];
    
          console.log("字段内容：", {
            ziduans: record.ziduans,
            moban: record.moban,
            moxing: record.moxing, // 是 Many2one，会是 ID
            moxing_model_name: record.moxing_model_name,
          });

        await  jiazaihprint();
        let suiji=randomString();
           
        
        let cfdt= transformFields(JSON.parse(record.ziduans) );
    
     
     
       let mbsj=record.moban;


  
       var configElementTypeProvider = (function () {
        return function (options) {
          var addElementTypes = function (context) {
            
            context.addPrintElementTypes(suiji, [
              new hiprint.PrintElementTypeGroup("业务数据", cfdt),

              new hiprint.PrintElementTypeGroup("辅助", [
                {
                  tid: "configModule.hline",
                  title: "横线",
                  type: "hline",
                },
                {
                  tid: "configModule.vline",
                  title: "竖线",
                  type: "vline",
                },
                {
                  tid: "configModule.rect",
                  title: "矩形",
                  type: "rect",
                },
                {
                  tid: "testModule.oval",
                  title: "椭圆",
                  type: "oval",
                },
              ]),
            ]);
          };

          return {
            addElementTypes: addElementTypes,
          };
        };
      })();
      hiprint.init({
        providers: [new configElementTypeProvider()],
      });
 



       var testTemplate = new hiprint.PrintTemplate({
        template:JSON.parse(record.moban) ,
      });

      const records1 = await orm.webRead(record.moxing_model_name, options.additionalContext.active_ids, {context:options.additionalContext,specification:buildSpecification(JSON.parse(record.ziduans))});
      console.log("模版", JSON.parse(record.moban) );
      console.log("数据内容：", transformData(records1));

     testTemplate.print( transformData(records1));
    
          // 你可以在这里做进一步处理...
    
        } catch (error) {
          notification.add(`出错：${error.message}`, { type: "danger" });
        }
        options.onClose();
        return true;
    });